package com.imddysc.spbbatchitemreaderxml;

import java.util.HashMap;
import java.util.Map;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.batch.item.xml.StaxEventItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.xstream.XStreamMarshaller;
import org.springframework.validation.BindException;

@Configuration
@EnableBatchProcessing
public class XmlItemReaderDemo {
	
	@Autowired
	private JobBuilderFactory jobBuilderFactory;
	
	@Autowired
	private StepBuilderFactory stepBuilderFactory;
	
	
	@Autowired
	@Qualifier("xmlFileWriter")
	private ItemWriter<Customer> xmlFileWriter;
	
	@Bean
	public Job xmlItemReaderDemoJob() {
		return jobBuilderFactory.get("xmlItemReaderDemoJob")
				.start(xmlItemReaderDemoStep())
				.build();
	}

	@Bean
	public Step xmlItemReaderDemoStep() {
		return stepBuilderFactory.get("xmlItemReaderDemoStep")
				.<Customer,Customer>chunk(5)
				.reader(xmlFileReader())
				.writer(xmlFileWriter)
				.build();
	}

	@Bean
	@StepScope
	public StaxEventItemReader<Customer> xmlFileReader() {
		StaxEventItemReader<Customer> reader = new StaxEventItemReader<Customer>();
		reader.setResource(new ClassPathResource("customer.xml"));//指定文件
		//指定要处理的数据根标签，不是xml的根标签
		reader.setFragmentRootElementName("customer");
		//把xml转成对象
		XStreamMarshaller unmarshaller = new XStreamMarshaller();
		Map<String,Class> map = new HashMap<>();
		map.put("customer", Customer.class);
		unmarshaller.setAliases(map);
		reader.setUnmarshaller(unmarshaller);
		
		return reader;
	}


}
